package com.pubg.filter;

import com.pubg.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 安全验证
 */
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        //谁都没有权限
        boolean isFlag = false;
        //验证session有效性
        Object sessionObj = session.getAttribute("user_admin");
        if (null == sessionObj){
            doMPath(request,response);
        }else{
           try{
               User user = (User) sessionObj;
               if (user != null){
                   isFlag = true;
               }
           }catch (Exception e){
               isFlag=false;
               doMPath(request,response);
           }
        }
        if (isFlag){
            filterChain.doFilter(request,response);
        }

    }

    private void doMPath(HttpServletRequest request,HttpServletResponse response) throws IOException{
        //ch04
        String path = request.getContextPath();
        //http://localhost:8080/ch04/
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

        PrintWriter out = response.getWriter();
        out.println("<script type='text/javascript'>alert('您没有权限,请先登录');location.href='"+basePath+"jquery404/login.html';</script>");
        out.flush();
        out.close();
    }
    @Override
    public void destroy() {

    }
}
